<?php
session_start();
// 权限验证
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    header('Location: login.php');
    exit;
}

// 数据库配置
$host = 'localhost';
$dbname = 'itops_help1_center';
$username = 'itops_help1_center';
$password = 'itops_help1_center';

// 表名定义（与数据库一致）
$articleTable = 'article'; // 文章表名（已确认正确）
$categoryTable = 'categories'; // 请根据实际分类表名修改（如之前错误提示，原category表不存在）

$articles = [];
$categories = [];
$error = '';
$success = '';

// 验证文章表是否存在（新增：提前检测表存在性）
function checkTableExists($pdo, $tableName) {
    try {
        $stmt = $pdo->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = :table");
        $stmt->execute([':table' => $tableName]);
        return $stmt->fetch() ? true : false;
    } catch (PDOException $e) {
        return false;
    }
}

// 处理删除操作
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    try {
        $pdo = new PDO(
            "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
            $username,
            $password,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );

        // 先验证文章表是否存在
        if (!checkTableExists($pdo, $articleTable)) {
            throw new Exception("文章表不存在（表名：$articleTable），无法执行删除操作");
        }

        $stmt = $pdo->prepare("DELETE FROM $articleTable WHERE id = :id");
        $stmt->execute([':id' => $id]);
        header('Location: article.php?success=文章已删除');
        exit;
    } catch (Exception $e) {
        $error = "删除失败：" . $e->getMessage();
    }
}

// 加载分类列表（使用正确的分类表名）
try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    if (!checkTableExists($pdo, $categoryTable)) {
        throw new Exception("分类表不存在（表名：$categoryTable），请检查表名是否正确");
    }

    $stmt = $pdo->query("SELECT id, name FROM $categoryTable ORDER BY sort_order ASC");
    if ($stmt instanceof PDOStatement) {
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $categories = [];
        $error = "分类数据加载失败：查询返回无效结果";
    }
} catch (Exception $e) {
    $error = "分类加载失败：" . $e->getMessage();
    $categories = [];
}

// 加载文章列表（使用正确的文章表名）
try {
    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // 先验证文章表是否存在
    if (!checkTableExists($pdo, $articleTable)) {
        throw new Exception("文章表不存在（表名：$articleTable），请检查表名是否正确");
    }

    $where = [];
    $params = [];
    
    if (isset($_GET['category_id']) && $_GET['category_id'] > 0) {
        $where[] = "a.category_id = :cid";
        $params[':cid'] = (int)$_GET['category_id'];
    }
    
    if (isset($_GET['keyword']) && !empty($_GET['keyword'])) {
        $where[] = "a.title LIKE :keyword";
        $params[':keyword'] = "%" . trim($_GET['keyword']) . "%";
    }
    
    $whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";
    
    // 关联查询：文章表（article）关联分类表（$categoryTable）
    $sql = "SELECT a.*, c.name as category_name 
            FROM $articleTable a 
            LEFT JOIN $categoryTable c ON a.category_id = c.id 
            $whereSql 
            ORDER BY a.create_time DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    if ($stmt instanceof PDOStatement) {
        $articles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } else {
        $articles = [];
        $error = "文章数据加载失败：查询返回无效结果";
    }
} catch (Exception $e) {
    $articles = [];
    $error = "文章加载失败：" . $e->getMessage();
}

// 接收提示信息
if (isset($_GET['success'])) $success = $_GET['success'];
if (isset($_GET['error'])) $error = $_GET['error'];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章管理 - IT知识库管理系统</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 统一样式（保持与之前一致） */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: #F1F5F9;
            color: #1E293B;
            line-height: 1.5;
        }
        
        .admin-container {
            display: flex;
            min-height: 100vh;
        }
        
        .admin-sidebar {
            width: 240px;
            background-color: #1E293B;
            color: white;
            padding: 1.5rem 0;
            flex-shrink: 0;
        }
        
        .sidebar-logo {
            display: flex;
            align-items: center;
            padding: 0 1.5rem 1.5rem;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            margin-bottom: 1rem;
        }
        
        .sidebar-logo i {
            font-size: 1.5rem;
            margin-right: 0.75rem;
            color: #38BDF8;
        }
        
        .nav-list {
            list-style: none;
        }
        
        .nav-item {
            margin-bottom: 0.25rem;
        }
        
        .nav-link {
            display: flex;
            align-items: center;
            padding: 0.75rem 1.5rem;
            color: #CBD5E1;
            text-decoration: none;
            transition: all 0.2s;
        }
        
        .nav-link:hover, .nav-link.active {
            background-color: #334155;
            color: white;
        }
        
        .nav-link i {
            width: 1.25rem;
            margin-right: 0.75rem;
        }
        
        .admin-content {
            flex: 1;
            padding: 1.5rem;
            overflow-y: auto;
        }
        
        .content-wrapper {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #E2E8F0;
        }
        
        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .btn {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 0.375rem;
            font-weight: 500;
            text-decoration: none;
            cursor: pointer;
            border: none;
            font-size: 0.875rem;
        }
        
        .btn-primary {
            background-color: #3B82F6;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #2563EB;
        }
        
        .btn-outline {
            background-color: transparent;
            border: 1px solid #94A3B8;
            color: #64748B;
        }
        
        .btn-danger {
            background-color: #EF4444;
            color: white;
        }
        
        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        
        .message {
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
        }
        
        .message-success {
            background-color: #ECFDF5;
            color: #059669;
            border: 1px solid #D1FAE5;
        }
        
        .message-error {
            background-color: #FEF2F2;
            color: #DC2626;
            border: 1px solid #FEE2E2;
        }
        
        .message i {
            margin-right: 0.5rem;
        }
        
        .form-card {
            background: white;
            padding: 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .inline-fields {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            align-items: flex-end;
        }
        
        .form-group {
            flex: 1;
            min-width: 200px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: #64748B;
        }
        
        .form-control {
            width: 100%;
            padding: 0.5rem 0.75rem;
            border: 1px solid #CBD5E1;
            border-radius: 0.375rem;
            font-size: 0.875rem;
        }
        
        .table-container {
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th,
        .data-table td {
            padding: 0.75rem 1rem;
            text-align: left;
            border-bottom: 1px solid #E2E8F0;
        }
        
        .data-table th {
            background-color: #F8FAFC;
            font-weight: 600;
            color: #64748B;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        @media (max-width: 768px) {
            .admin-container {
                flex-direction: column;
            }
            
            .admin-sidebar {
                width: 100%;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 1rem;
            }
            
            .table-container {
                overflow-x: auto;
            }
            
            .data-table {
                min-width: 600px;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <!-- 侧边栏 -->
        <aside class="admin-sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-cogs"></i>
                    <span>知识库管理</span>
                </div>
            </div>
            <ul class="nav-list">
                <li class="nav-item">
                    <a href="index.php" class="nav-link">
                        <i class="fas fa-home"></i>
                        <span>管理首页</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="article.php" class="nav-link active">
                        <i class="fas fa-file-alt"></i>
                        <span>文章管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="category.php" class="nav-link">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="version.php" class="nav-link">
                        <i class="fas fa-sync-alt"></i>
                        <span>版本管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="user.php" class="nav-link">
                        <i class="fas fa-users"></i>
                        <span>用户管理</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a href="logout.php" class="nav-link">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
        </aside>

        <!-- 内容区 -->
        <main class="admin-content">
            <div class="content-wrapper">
                <div class="page-header">
                    <h1 class="page-title">文章管理</h1>
                    <a href="article_add.php" class="btn btn-primary">
                        <i class="fas fa-plus"></i>新增文章
                    </a>
                </div>

                <!-- 提示信息 -->
                <?php if ($success): ?>
                    <div class="message message-success">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo $success; ?></span>
                    </div>
                <?php endif; ?>
                <?php if ($error): ?>
                    <div class="message message-error">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo $error; ?></span>
                    </div>
                <?php endif; ?>

                <!-- 筛选表单 -->
                <div class="form-card">
                    <form method="get" action="article.php" class="inline-fields">
                        <div class="form-group">
                            <label class="form-label">分类筛选</label>
                            <select name="category_id" class="form-control">
                                <option value="0">全部分类</option>
                                <?php foreach ($categories as $cate): ?>
                                    <option value="<?php echo $cate['id']; ?>" 
                                        <?php echo isset($_GET['category_id']) && $_GET['category_id'] == $cate['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cate['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">关键词搜索</label>
                            <input type="text" name="keyword" class="form-control" 
                                placeholder="搜索文章标题" 
                                value="<?php echo isset($_GET['keyword']) ? htmlspecialchars($_GET['keyword']) : ''; ?>">
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i>筛选
                            </button>
                            <a href="article.php" class="btn btn-outline" style="margin-left: 8px;">
                                <i class="fas fa-redo"></i>重置
                            </a>
                        </div>
                    </form>
                </div>

                <!-- 文章列表 -->
                <div class="table-container">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>标题</th>
                                <th>分类</th>
                                <th>发布时间</th>
                                <th>状态</th>
                                <th style="width: 180px;">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($articles)): ?>
                                <tr>
                                    <td colspan="6" style="text-align: center; padding: 30px;">暂无文章记录</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($articles as $article): ?>
                                    <tr>
                                        <td><?php echo $article['id']; ?></td>
                                        <td><?php echo htmlspecialchars($article['title']); ?></td>
                                        <td><?php echo htmlspecialchars($article['category_name'] ?? '未分类'); ?></td>
                                        <td><?php echo $article['create_time']; ?></td>
                                        <td>
                                            <?php echo $article['status'] == 1 ? 
                                                '<span style="color: #36D399;">已发布</span>' : 
                                                '<span style="color: #94A3B8;">草稿</span>'; ?>
                                        </td>
                                        <td class="action-buttons">
                                            <a href="article_edit.php?id=<?php echo $article['id']; ?>" class="btn btn-outline btn-sm">
                                                <i class="fas fa-edit"></i>编辑
                                            </a>
                                            <a href="javascript:confirmDelete(<?php echo $article['id']; ?>)" class="btn btn-danger btn-sm">
                                                <i class="fas fa-trash"></i>删除
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <script>
        function confirmDelete(id) {
            if (confirm('确定要删除这篇文章吗？删除后不可恢复。')) {
                window.location.href = "article.php?action=delete&id=" + id;
            }
        }
    </script>
</body>
</html>